<?php
namespace app\index\model;

use think\Model;
use think\DB;

class User extends Model
{
    public function getUserInfo($field,$uid){
        return DB::name('user')->where($field,$uid)->find();
    }

    /**
     * 登录验证
     * @param $tel 用户手机
     * @param $pass 密码
     * @return mixed 登录是否成功
     */
    public function toCheckLogin($tel,$pass){
        $check_tel_res = $this->getUserId($tel);
        $login['status'] = 1;
        $login['content'] = '验证成功';
        if($check_tel_res){
            $check_pass_res = DB::name('user')->where('password',md5($pass))->find();
            if($check_pass_res){
                return $login;
            }else{
                $login['status'] = 0;
                $login['content'] = '密码错误';
                return $login;
            }
        }else{
            $login['status'] = 0;
            $login['content'] = '账号不存在';
            return $login;
        }
    }

    /**
     * 修改密码
     * @param $tel  用户手机
     * @param $oldpassword 旧密码
     * @param $newpassword 新密码
     * @return int|string  修改是否成功 0|1
     */
    public function changePassword($tel,$oldpassword,$newpassword){
        $check_res = $this->toCheckLogin($tel,$oldpassword);
        if($check_res['status']){
            $map = [
                'password' => MD5("$newpassword"),
            ];
            return DB::name('user')->where('tel',$tel)->update($map);
        }
        return $check_res['status'];
    }

    //注册
    public function Register($tel,$password){
        $user_info = $this->getUserInfo('tel',$tel);
        if(empty($user_info)){
            $map = [
                'tel' => $tel,
                'password' => MD5($password),
                'name' => $tel,
                'UnionID' => $tel,
            ];
            return DB::name('user')->insert($map);
        }

    }

    public function updateInfo($tel,$icon)
    {
        $user_info = $this->getUserInfo('tel',$tel);
        if(empty($user_info)){
            $map = [
                'tel' => $tel,
                'image' => $icon,
            ];
            return DB::name('user')->where('tel',$tel)->update($map);
        }
    }

}